package com.game.caro.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.game.caro.data.*;

public class Server
{
	//choose port number
	private static final int PORT=1234;
	
	// Array ioSessions
	public static HashMap<Long, IoSession> ioSessions = new HashMap<Long, IoSession>();

	
	// Array rooms 
	public static HashMap<Integer, PlayRoom> rooms = new HashMap<Integer, PlayRoom>();
	
	public static DatabaseAccess databaseAccess = new DatabaseAccess();
	
	public Server()
	{
		// TODO Auto-generated method stubs		
		NioSocketAcceptor acceptor=new NioSocketAcceptor();
		DefaultIoFilterChainBuilder chain=acceptor.getFilterChain();
		MdcInjectionFilter mdcInjectionFilter=new MdcInjectionFilter();
		chain.addLast("mdc",mdcInjectionFilter);
		chain.addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory()));
		chain.addLast("logger",new LoggingFilter());
		
		//Binds
		acceptor.setHandler(new CaroProtocolHandler());
		try {
			acceptor.bind(new InetSocketAddress(PORT));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Listening on port:"+PORT);
		System.out.println("Loggin ON");
		
		// Khoi tao cac phong choi lay tu csdl
		databaseAccess.initRoom();
	}

	public static HashMap<Long, IoSession> getIoSessions() 
	{
		return ioSessions;
	}
	
	public static HashMap<Integer, PlayRoom> getRooms() 
	{
		return rooms;
	}

	

}
